<?php
class Kelurahan extends CI_Controller {

	function __construct()
	{
		parent::__construct();	
		$this->load->helper('flexigrid');
		$this->load->library('flexigrid');
		$this->load->library('form_validation');
		$this->load->model('kelurahan_model');	
		$this->load->model('kecamatan_model');
		$this->load->model('user_man_model');
	}
	
	function index($id_kecamatan)
	{
		$allkecamatan = $this->kecamatan_model->get_kecamatanID($id_kecamatan);
		foreach($allkecamatan->result() as $row){
			$kecamatan = $row->NAMA_KECAMATAN;
		}
		//ver lib
		
		/*
		 * 0 - display name
		 * 1 - width
		 * 2 - sortable
		 * 3 - align
		 * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
		 */
		$colModel['no'] = array('No',40,TRUE,'center',0);
		$colModel['ubah'] = array('Edit',50,FALSE,'center',0);
		$colModel['NAMA_KELURAHAN'] = array('Kelurahan / Desa',100,FALSE,'center',1);
		
		/*
		 * Aditional Parameters
		 */
		$gridParams = array(
		'width' => 'auto',
		'height' => '355',
		'rp' => 15,
		'rpOptions' => '[10,15,20,25,40]',
		'pagestat' => 'Displaying: {from} to {to} of {total} items.',
		'blockOpacity' => 0.5,
		'title' => 'Daftar Kelurahan pada Kecamatan '.$kecamatan
		);
		
		/*
		 * 0 - display name
		 * 1 - bclass
		 * 2 - onpress
		 */
		$buttons[] = array('Tambah','add','kelurahan_js');
		$buttons[] = array('Hapus','delete','kelurahan_js');
		$buttons[] = array('separator');
		$buttons[] = array('Select All','add','kelurahan_js');
		$buttons[] = array('Deselect All','delete','kelurahan_js');
		$buttons[] = array('separator');
		$buttons[] = array('Kembali ke Kecamatan','delete','kelurahan_js');
		$buttons[] = array('separator');
		
		//Build js
		//View helpers/flexigrid_helper.php for more information about the params on this function
		$grid_js = build_grid_js('flex1',site_url("/kelurahan/kelurahan_grid/".$id_kecamatan),$colModel,'no','asc',$gridParams,$buttons);
		
		$data['title'] = "Contoh Flexigrid";
		$data['info'] = "Flexigrid";
		$data['js_grid'] = $grid_js;
		$data['version'] = "0.36";
		$data['download_file'] = "Flexigrid_CI_v0.36.rar";
		
		$data['added_js'] = 
			"
			<script type='text/javascript'>
						
			function kelurahan_js(com,grid)
			{
				if (com=='Select All')
				{
					$('.bDiv tbody tr',grid).addClass('trSelected');
				}
				
				if (com=='Deselect All')
				{
					$('.bDiv tbody tr',grid).removeClass('trSelected');
				}
				
				if (com=='Kembali ke Kecamatan')
				{
					location.href='".base_url()."index.php/kecamatan'; 
				}
				
				if (com=='Tambah')
				{
					location.href='".base_url()."index.php/kelurahan/input_kelurahan/".$id_kecamatan."'; 
				}
				
				if (com=='Hapus')
				{
				   if($('.trSelected',grid).length>0){
					   if(confirm('Anda yakin ingin menghapus ' + $('.trSelected',grid).length + ' buah data?')){
							var items = $('.trSelected',grid);
							var itemlist ='';
							for(i=0;i<items.length;i++){
								itemlist+= items[i].id.substr(3)+',';
							}
							$.ajax({
							   type: 'POST',
							   url: '".site_url('/kelurahan/delete_kelurahan')."',
							   data: 'items='+itemlist,
							   success: function(data){
								$('#flex1').flexReload();
								alert(data);
							   }
							});
						}
					} else {
						return false;
					} 
				}          
			}
			</script>
			";
		
		/* $data['notification'] = "";
		if($this->session->userdata('notification')!=''){
			$data['notification'] = "
				<script>
					$(document).ready(function() {
						$.growlUI('Pesan :', '".$this->session->userdata('notification')."'); 
					});
				</script>
			";
		}//end if */	
		
		$data['content'] = $this->load->view('grid',$data,true);
		$this->load->view('main',$data);
		//$this->load->view('grid',$data);
		//$this->load->view('flexigrid',$data);
	}
	
	function kelurahan_grid($id_kecamatan)
	{
		//List of all fields that can be sortable. This is Optional.
		//This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors.
		$valid_fields = array('IDKELURAHAN','NAMA_KELURAHAN');
		
		$atts = array(
              'width'      => '600',
              'height'     => '300',
              'scrollbars' => 'no',
              'status'     => 'no',
              'resizable'  => 'no',
              'screenx'    => '0',
              'screeny'    => '0'
            );
		
		$this->flexigrid->validate_post('IDKELURAHAN','asc',$valid_fields);

		$records = $this->kelurahan_model->get_kelurahan_grid($id_kecamatan);
		
		$this->output->set_header($this->config->item('json_header'));
		$no = 1;
		$unitid = $this->session->userdata('unitid');
		/*
		 * Json build WITH json_encode. If you do not have this function please read
		 * http://flexigrid.eyeviewdesign.com/index.php/flexigrid/example#s3 to know how to use the alternative
		 */
		foreach ($records['records']->result() as $row)
		{
			$record_items[] = array($row->IDKELURAHAN,
			$no,'<a href=\''.site_url().'/kelurahan/edit_kelurahan/'.$id_kecamatan.'/'.$row->IDKELURAHAN.'/\'><img border=\'0\' src=\''.base_url().'images/main/28.png\'></a>',
			'<div align="center">'.$row->NAMA_KELURAHAN.'</div>'
			);
			$no++;
		}
		//Print please
		if(isset($record_items))
				$this->output->set_output($this->flexigrid->json_build($records['record_count'],$record_items));
			else
				$this->output->set_output('{"page":"1","total":"0","rows":[]}');
	}
	
	function cek_validasi() {	
			// Setting Rules
			$this->form_validation->set_rules('kelurahan', 'Kelurahan', 'required');

			$this->form_validation->set_message('required', 'Kolom %s harus diisi!!');
			// Setting Delimiter
			$this->form_validation->set_error_delimiters('<li class="error">', '</li>');
			return $this->form_validation->run();
	}
	
	
	function cek_validasi_edit() {	
			// Setting Rules
			$this->form_validation->set_rules('kelurahan', 'Kelurahan', 'required');

			// Setting Error Message
			$this->form_validation->set_message('required', 'Kolom %s harus diisi!!');
			$this->form_validation->set_message('numeric', 'Kolom %s harus diisi dengan karakter angka saja, desimal menggunakan titik (.)');
			
			// Setting Delimiter
			$this->form_validation->set_error_delimiters('<li class="error">', '</li>');
			return $this->form_validation->run();
			
	}
	
	
	function input_kelurahan($id_kecamatan)
    {
		$this->load->library('session');
    	$data['kecamatan'] = $this->kecamatan_model->get_kecamatan();
		if ($this->cek_validasi() == FALSE){
				$data['status'] = 'new';
				$data['id_kecamatan'] = $id_kecamatan;
				$this->session->set_userdata('id_kecamatan',$id_kecamatan);
				$data['user'] = $this->user_man_model->get_user();
				$data['content'] = $this->load->view('form_kelurahan',$data,true);
				$this->load->view('main',$data);
			}
			else{
				$this->insert_kelurahan($id_kecamatan);
			}            
    }
	
	function insert_kelurahan($id_kecamatan){	
		$datakelurahan = array(
			'IDKECAMATAN'				=> $id_kecamatan,
			'NAMA_KELURAHAN'			=> $this->input->post('kelurahan'),
			'STATUS' 					=> 1			
		);

		$this->kelurahan_model->add_kelurahan($datakelurahan);
		redirect('kelurahan/kelurahan/'.$id_kecamatan); 
	}
	
	function edit_kelurahan($id_kecamatan,$id_kelurahan)
    {
    	$data['kecamatan'] = $this->kecamatan_model->get_kecamatan();
 		$data['kelurahan'] = $this->kelurahan_model->get_kelurahan();
		$this->session->set_userdata('id_kelurahan',$id_kelurahan);
		if ($this->cek_validasi_edit() == FALSE){
				$data['status'] = 'edit';
				$data['id_kecamatan'] = $id_kecamatan;
				$data['id_kelurahan'] = $id_kelurahan;
				$data['user'] = $this->user_man_model->get_user();
				$data['kelurahan'] = $this->kelurahan_model->get_kelurahanID($id_kelurahan);
				$data['content'] = $this->load->view('form_kelurahan',$data,true);
				$this->load->view('main',$data);
			}
			else{
				$this->update_kelurahan($id_kelurahan,$id_kecamatan);
			}            
    }
	
	function update_kelurahan($id_kelurahan,$id_kecamatan){
		$data = array(
			'NAMA_KELURAHAN'			=> $this->input->post('kelurahan'),
			'STATUS' 					=> 1
		);
		
		$this->kelurahan_model->edit_kelurahan($id_kelurahan,$data);
		redirect('kelurahan/kelurahan/'.$id_kecamatan); 
	}
	
	//Delete
	function delete_kelurahan()
	{
		$kelurahan_ids_post_array = explode(",",$this->input->post('items'));
		$msg = '';
		foreach($kelurahan_ids_post_array as $index => $kelurahan_id){
			if (isset($kelurahan_id) && $kelurahan_id != "") {
				$this->kelurahan_model->delete_kelurahan($kelurahan_id);
						
			
			$msg .= "Kelurahan dengan id (".$kelurahan_id.") telah berhasil dihapus.\n";
			}
		}
		$this->output->set_header($this->config->item('ajax_header'));
		$this->output->set_output($msg);
	}
    
	function cek_dropdown($value){
		if($value === '0'){
			$this->form_validation->set_message('cek_dropdown', 'Kolom %s harus diisi!!');
			return FALSE;
		}
		else{
			return TRUE;
		}
	}//end cek_dropdown
	
	
	
	function cek_data($value){
		$nama_kelurahan = $this->input->post('nama_kelurahan');

		$sql =  $this->db->query("SELECT COUNT(NAMA_KELURAHAN) AS CEK FROM KELURAHAN WHERE NAMA_KELURAHAN = '".$nama_kelurahan."' AND STATUS = 1");
		
		$CEK='';
			
		foreach ($sql->result() as $rows){
			$CEK=$rows->CEK;
		}
		
		if($CEK==0){
				return TRUE;
		}else{
				$this->form_validation->set_message('cek_data', 'Data %s sudah diinisialisasikan!!!');
				return FALSE;
		}		
		
	}
  
	function cek_data_edit($value){
		$nama_kelurahan = $this->input->post('nama_kelurahan');
		
		
		
		$sql =  $this->db->query("SELECT COUNT(NAMA_KELURAHAN) AS CEK FROM KELURAHAN WHERE NAMA_KELURAHAN = '".$nama_kelurahan."' AND STATUS = 1");
		$data = $this->kelurahan_model->get_kelurahanID($this->session->userdata('id_kelurahan'));
		
		
		$CEK='';
			
		foreach ($sql->result() as $rows){
			$CEK=$rows->CEK;
		}
		
		$data_lama='';
		foreach ($data->result() as $rows){
			$data_lama=$rows->NAMA_KELURAHAN;
		}
		
		
		if($nama_kelurahan == $data_lama)
		{
			return TRUE;
		}
		else{
			if($CEK==0){
					return TRUE;
			}else{
					$this->form_validation->set_message('cek_data_edit', 'Data %s sudah diinisialisasikan!!!');
					return FALSE;
			}		
		}
	}
  
}
?>
